package cn.sieis.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.sieis.pojo.Source;
import cn.sieis.service.source.SourceService;
import cn.sieis.tools.DateUtil;
import cn.sieis.tools.FastDFSClient;

@Controller
public class SourceController {

	@Autowired
	private SourceService sourceService;

	@PostMapping(value = "/sourceUpload")
	public String sourceUpload(MultipartFile file, HttpServletRequest request) {
		Source source = new Source();
//          String path = request.getServletContext().getRealPath("source");
//          String path = "D:/upload/source/";
//        source.setPubtime(DateUtil.getNowTime());
		String filename = file.getOriginalFilename();
		source.setFilename(filename);

		// 上传文件的关键两行代码
		String str = FastDFSClient.uploadFile(file);
		String filepath = FastDFSClient.getResAccessUrl(str);
		source.setPubtime(DateUtil.getNowTime());
		source.setFilepath(filepath);
		boolean result = sourceService.addSource(source);
		if (result) {
			try {
//                file.transferTo(fileDir);
				return "admin/uploadSuccess";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return "failed";
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@GetMapping(value = "/getSourceListByUser")
	public String getSourceListByUser(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, ModelMap model) {
		PageHelper.startPage(pageNum, 5);
		PageHelper.orderBy("pubtime desc");

		List<Source> sourceList = sourceService.getSourceList();

		PageInfo pageInfo = new PageInfo(sourceList);

		model.addAttribute("sourceList", pageInfo);
		return "frontPage/sourceList";
	}

	/**
	 * 管理员
	 * 
	 * @param pageNum
	 * @param model
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@GetMapping(value = "/getSourceList")
	public String getSourceList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, ModelMap model) {

		PageHelper.startPage(pageNum, 5);
		PageHelper.orderBy("pubtime desc");

		List<Source> sourceList = sourceService.getSourceList();

		PageInfo pageInfo = new PageInfo(sourceList);

		model.addAttribute("sourceList", pageInfo);
		return "admin/source/sourceList";
	}

	@GetMapping(value = "/deleteSourceById")
	public String deleteSourceById(Integer id, ModelMap model) {

		Source source = sourceService.getSourceById(id);
		if (source != null) {
			// 先从fastdfs文件服务器删除文件，在删除数据库中的数据
			boolean result = FastDFSClient.deleteFile(source.getFilepath());
			if (result) {
				sourceService.deleteSourceById(id);
				return "forward:/getSourceList";
			}
			return "failed";
		}

		return "failed";
	}

	// http://114.55.93.197/group1/M00/00/00/rBAmt11xuwqAEBxFAANalRLpucE09.docx
	@GetMapping(value = "/downloadSourceById")
	public String downloadSourceById(@RequestParam("id") Integer id, HttpServletResponse response) throws IOException {
		// 拿到系统默认的临时文件路径
		String tmpdir = System.getProperty("java.io.tmpdir");
		Source source = sourceService.getSourceById(id);
		response.reset();
		response.setContentType("application/x-download");
		BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(source.getFilename(), "UTF-8"));
		File file = new File(tmpdir + source.getFilename());
		byte[] downloadFileWeb = FastDFSClient.downloadFileWeb(source.getFilepath(), file);
		BufferedInputStream fin = new BufferedInputStream(new ByteArrayInputStream(downloadFileWeb));
		int length;
		byte[] content = new byte[1024];
		while ((length = fin.read(content, 0, content.length)) != -1) {
			outputStream.write(content, 0, length);
		}
		fin.close();
		outputStream.close();
		return "forward:/getSourceListByUser";

	}

	@GetMapping(value = "/downloadSourceByStorageId")
	public String downloadStorageId(@RequestParam("storageId") String storageId, HttpServletResponse response, Model model) throws IOException {
		
		try {
			if(StringUtils.isBlank(storageId)) {
				storageId="http://172.21.0.12/group1/M00/00/00/rBUADF6rHRGAaaGkAAhguxiLn6E195.JPG";
			}
			// 拿到系统默认的临时文件路径
			String tmpdir = System.getProperty("java.io.tmpdir");
			Source source = sourceService.getSourceByStrageId(storageId);
			response.reset();
			response.setContentType("application/x-download");
			BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
			response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(source.getFilename(), "UTF-8"));
			File file = new File(tmpdir + source.getFilename());
			byte[] downloadFileWeb = FastDFSClient.downloadFileWeb(source.getFilepath(), file);
			BufferedInputStream fin = new BufferedInputStream(new ByteArrayInputStream(downloadFileWeb));
			int length;
			byte[] content = new byte[1024];
			while ((length = fin.read(content, 0, content.length)) != -1) {
				outputStream.write(content, 0, length);
			}
			fin.close();
			outputStream.close();
			  model.addAttribute("result","下载成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "forward:/back/project/projectlist";

	}

}
